<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
import {
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  ClusterOutlined,
  DatabaseOutlined,
  ApartmentOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {
  GetClusterInfo,
  GetClusterResourceUsage,
  GetClusterNodes,
  GetClusterNamespaces
} from "@/api/cluster";

// 定义props
const props = defineProps({
  clusterId: {
    type: String,
    required: true
  },
});

// --- Loading 状态 ---
const loading = ref({
  clusterInfo: true,
  resources: true,
  nodes: true,
  namespaces: true,
});

// --- 响应式数据 ---

// 定义一下数据格式
interface ClusterInfo {
  name: string;
  status: string;
  version: string;
  type: string;
}

interface ClusterResourceUsage {
  cpu: { used: number; total: number; unit: string };
  memory: { used: number; total: number; unit: string };
  pods: { used: number; total: number; unit: string };
  gpu: { used: number; total: number; unit: string }; // 新增 GPU 字段
}

interface ClusterNode {
  name: string;
  status: string;
  role: string;
  ip: string;
  version: string;
}

interface ClusterNamespace {
  name: string;
  status: string;
  labels: {};
}

// 集群基本信息
const clusterInfo = ref<ClusterInfo>({});

// 节点信息
const nodes = ref<ClusterNode[]>([]);

// 命名空间信息
const namespaces = ref<ClusterNamespace[]>([]);

// 资源使用情况
const resourceUsage = ref<ClusterResourceUsage>({
  cpu: { used: 0, total: 1, unit: 'Cores' },
  memory: { used: 0, total: 1, unit: 'GiB' },
  pods: { used: 0, total: 1, unit: '' },
  gpu: { used: 0, total: 1, unit: 'MB' }, // 新增 GPU 初始值
});

// --- 计算属性 ---
// 计算节点状态
const readyNodes = computed(() => nodes.value.filter(n => n.status === 'Ready').length);
const totalNodes = computed(() => nodes.value.length);

// 计算资源使用百分比
const cpuPercentage = computed(() => resourceUsage.value.cpu.total > 0 ? Math.round((resourceUsage.value.cpu.used / resourceUsage.value.cpu.total) * 100) : 0);
const memoryPercentage = computed(() => resourceUsage.value.memory.total > 0 ? Math.round((resourceUsage.value.memory.used / resourceUsage.value.memory.total) * 100) : 0);
const podsPercentage = computed(() => resourceUsage.value.pods.total > 0 ? Math.round((resourceUsage.value.pods.used / resourceUsage.value.pods.total) * 100) : 0);
const gpuPercentage = computed(() => resourceUsage.value.gpu.total > 0 ? Math.round((resourceUsage.value.gpu.used / resourceUsage.value.gpu.total) * 100) : 0); // 新增 GPU 百分比计算


// antd table的列定义
const nodeColumns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '角色', dataIndex: 'role', key: 'role' },
  { title: 'IP', dataIndex: 'ip', key: 'ip' },
  { title: 'K8s版本', dataIndex: 'version', key: 'version' },
];

const namespaceColumns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

// 使用真实API异步加载数据
const fetchData = () => {
  // 移除 async/await 链式调用，让所有请求并行发出
  // 每个请求独立处理自己的 then/catch/finally

  // 1. 加载集群信息
  GetClusterInfo(props.clusterId)
      .then(infoRes => {
        if (infoRes.code === 0 && infoRes.data) {
          clusterInfo.value = {
            name: infoRes.data.cluster_model.name || '未知集群',
            status: (infoRes.data.cluster_model.status === 'Ready' ? 'Running' : 'else') || 'Unknown',
            version: infoRes.data.cluster_model.kube_version || 'N/A',
            type: infoRes.data.cluster_model.type || 'N/A',
          };
        } else {
          message.error(infoRes.message || '获取集群信息失败');
        }
      })
      .catch(() => {
        message.error('请求集群信息API失败');
      })
      .finally(() => {
        loading.value.clusterInfo = false;
      });

  // 2. 加载资源使用情况
  GetClusterResourceUsage(props.clusterId)
      .then(resourceRes => {
        if (resourceRes.code === 0 && resourceRes.data.resource_ratio_map) {
          // console.log(resourceRes.data);
          resourceUsage.value = resourceRes.data.resource_ratio_map;
        } else {
          message.error(resourceRes.message || '获取资源使用情况失败');
        }
      })
      .catch(() => {
        message.error('请求资源使用情况API失败');
      })
      .finally(() => {
        loading.value.resources = false;
      });

  // 3. 加载节点信息
  GetClusterNodes(props.clusterId)
      .then(nodesRes => {
        if (nodesRes.code === 0 && nodesRes.data) {
          nodes.value = nodesRes.data;
        } else {
          message.error(nodesRes.message || '获取节点信息失败');
        }
      })
      .catch(() => {
        message.error('请求节点信息API失败');
      })
      .finally(() => {
        loading.value.nodes = false;
      });

  // 4. 加载命名空间信息
  GetClusterNamespaces(props.clusterId)
      .then(nsRes => {
        if (nsRes.code === 0 && nsRes.data) {
          namespaces.value = nsRes.data;
        } else {
          message.error(nsRes.message || '获取命名空间信息失败');
        }
      })
      .catch(() => {
        message.error('请求命名空间信息API失败');
      })
      .finally(() => {
        loading.value.namespaces = false;
      });
};


onMounted(() => {
  // 异步获取所有数据
  fetchData();
})

</script>

<template>
  <div class="dashboard-container">
    <!-- 第一行：集群状态和资源概览 -->
    <a-row :gutter="[16, 16]">
      <!-- 集群信息卡片 -->
      <a-col :xs="24" :sm="24" :md="12" :lg="8">
        <a-card title="集群状态" class="dashboard-card" :loading="loading.clusterInfo">
          <template #extra><a-button type="link">详情</a-button></template>
          <p><strong>名称:</strong> {{ clusterInfo.name }}</p>
          <p><strong>状态:</strong>
            <a-tag :color="clusterInfo.status === 'Running' ? 'green' : 'red'">
              <template #icon>
                <check-circle-outlined v-if="clusterInfo.status === 'Running'"/>
                <exclamation-circle-outlined v-else/>
              </template>
              {{ clusterInfo.status }}
            </a-tag>
          </p>
          <p><strong>Kubernetes 版本:</strong> {{ clusterInfo.version }}</p>
          <p><strong>类型:</strong> {{ clusterInfo.type }}</p>
        </a-card>
      </a-col>

      <!-- 资源使用率卡片 -->
      <a-col :xs="24" :sm="24" :md="12" :lg="16">
        <a-card title="核心资源使用率" class="dashboard-card" :loading="loading.resources">
          <a-row :gutter="[16, 16]">
            <a-col :span="8" class="resource-col">
              <a-progress type="dashboard" :percent="cpuPercentage" :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }"/>
              <div class="resource-text">CPU 使用率</div>
              <div class="resource-detail">{{ resourceUsage.cpu.used.toFixed(1) }} / {{ resourceUsage.cpu.total }} {{ resourceUsage.cpu.unit }}</div>
            </a-col>
            <a-col :span="8" class="resource-col">
              <a-progress type="dashboard" :percent="memoryPercentage" :stroke-color="{ '0%': '#87d068', '100%': '#108ee9' }"/>
              <div class="resource-text">内存使用率</div>
              <div class="resource-detail">{{ resourceUsage.memory.used.toFixed(1) }} / {{ resourceUsage.memory.total.toFixed(1) }} {{ resourceUsage.memory.unit }}</div>
            </a-col>
            <a-col :span="8" class="resource-col">
              <a-progress type="dashboard" :percent="gpuPercentage" :stroke-color="{ '0%': '#722ed1', '100%': '#f759ab' }"/>
              <div class="resource-text">GPU 使用率</div>
              <div class="resource-detail">{{ resourceUsage.gpu.used }} / {{ resourceUsage.gpu.total }} {{ resourceUsage.gpu.unit }}</div>
            </a-col>
<!--            <a-col :span="6" class="resource-col">-->
<!--              <a-progress type="dashboard" :percent="podsPercentage" :stroke-color="{ '0%': '#108ee9', '100%': '#ff4d4f' }"/>-->
<!--              <div class="resource-text">Pod 分配</div>-->
<!--              <div class="resource-detail">{{ resourceUsage.pods.used }} / {{ resourceUsage.pods.total }}</div>-->
<!--            </a-col>-->
          </a-row>
        </a-card>
      </a-col>
    </a-row>

    <!-- 第二行：节点和命名空间信息 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px;">
      <!-- 节点信息卡片 -->
      <a-col :xs="24" :lg="14">
        <a-card class="dashboard-card" :loading="loading.nodes">
          <template #title>
            <apartment-outlined /> 节点 ({{ readyNodes }} / {{ totalNodes }} Ready)
          </template>
          <a-table :dataSource="nodes" :columns="nodeColumns" :pagination="{ pageSize: 5 }" size="small" row-key="name">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="record.status === 'Ready' ? 'success' : 'error'">
                  <template #icon>
                    <check-circle-outlined v-if="record.status === 'Ready'"/>
                    <sync-outlined v-else spin/>
                  </template>
                  {{ record.status }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 命名空间卡片 -->
      <a-col :xs="24" :lg="10">
        <a-card class="dashboard-card" :loading="loading.namespaces">
          <template #title>
            <database-outlined /> 命名空间
          </template>
          <a-table :dataSource="namespaces" :columns="namespaceColumns" :pagination="{ pageSize: 5 }" size="small" row-key="name">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag color="blue">{{ record.status }}</a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped>
.dashboard-container {
  width: 100%;
  text-align: left;
}

.dashboard-card {
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  height: 100%;
}

.dashboard-card:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.dashboard-card p {
  margin-bottom: 12px;
  font-size: 14px;
}

.dashboard-card p:last-child {
  margin-bottom: 0;
}

.resource-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.resource-text {
  margin-top: 8px;
  font-weight: bold;
  font-size: 16px;
}

.resource-detail {
  font-size: 12px;
  color: #888;
}
</style>
